package com.whpu.mall.product.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whpu.common.constant.ProductConstant;
import com.whpu.common.utils.PageUtils;
import com.whpu.common.utils.Query;
import com.whpu.mall.product.dao.AttrAttrgroupRelationDao;
import com.whpu.mall.product.dao.AttrDao;
import com.whpu.mall.product.dao.AttrGroupDao;
import com.whpu.mall.product.dao.CategoryDao;
import com.whpu.mall.product.entity.AttrAttrgroupRelationEntity;
import com.whpu.mall.product.entity.AttrEntity;
import com.whpu.mall.product.entity.AttrGroupEntity;
import com.whpu.mall.product.entity.CategoryEntity;
import com.whpu.mall.product.service.AttrService;
import com.whpu.mall.product.service.CategoryService;
import com.whpu.mall.product.vo.AttrGroupRelationVO;
import com.whpu.mall.product.vo.AttrRespVo;
import com.whpu.mall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 级联保存
     *
     * @param attr
     */
    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        //将attr的字段的值封装到attrEntity,字段必须相同
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity); //保存基本数据
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId()); //前端传回的分组id
            relationEntity.setAttrId(attrEntity.getAttrId());
            //保存关联关系
            relationDao.insert(relationEntity);
        }


    }

    /**
     * 规格参数列表查询
     *
     * @param params
     * @param catelogId
     * @param attrType
     * @return
     */
    @Override
    public PageUtils queryAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        //1: 规格参数  0: 销售属性
        queryWrapper.eq("attr_type", "base".equalsIgnoreCase(attrType)
                ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if (catelogId != 0) {  //catlogId == 0 就说明从root查询
            queryWrapper.eq("catelog_id", catelogId);
        }
        //模糊查询,获取搜索条件
        String key = (String)params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        //添加分组和分类信息(AttrEntity里没有的字段)
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();

        List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo(); //最后返回的是这个
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            //规格参数才设置分组信息
            if ("base".equalsIgnoreCase(attrType)) {
                //设置分类和分组名
                //根据每个值去对应数据库查找, 避免使用连接查询
                //根据attr_id查找对应第三张表的数据,可以得到对应的分组id
                AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (relationEntity != null && relationEntity.getAttrGroupId() != null) {  //关联表为第三张表,所以relationEntity不为null就代表分组id也不为null
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());  //设置分组名
                }
            }

            //分类信息
            CategoryEntity categoryEntity = categoryDao.selectById(attrRespVo.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());  //最后转为数组

        pageUtils.setList(respVos);  //返回
        return pageUtils;
    }

    /**
     * 回显规格信息
     *
     * @param attrId
     * @return
     */
    @Override
    public AttrVo getAttrInfo(Long attrId) {
        AttrRespVo respVo = new AttrRespVo();  //最终返回的对象
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, respVo);
        //此时还缺两个字段: 分组id和分类完整路径
        //判断属性类型
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //设置分组信息
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (relationEntity != null) {
                respVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity groupEntity = attrGroupDao.selectById(relationEntity.getAttrId());
                if (groupEntity != null) {
                    respVo.setGroupName(groupEntity.getAttrGroupName());
                }
            }
        }

        //设置分类信息
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findGroupPath(catelogId);//查询分类完整路径
        respVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryService.getById(catelogId);
        if (categoryEntity != null) {
            respVo.setCatelogName(categoryEntity.getName());  //设置分类名
        }
        //设置分类信息
        return respVo;
    }

    /**
     * 修改规格信息
     *
     * @param attr
     */
    @Override
    @Transactional
    public void updateAttr(AttrVo attr) {
        //修改基本信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);  //修改本身
        //判断是否是规格参数/基本属性
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //修改关联表
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());
            //update pms_attr_attrgroup_relation set attr_group_id = ? where attr_id = ?
            Integer count = relationDao.selectCount(  //如果没查到信息则add, 有就update
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (count > 0) {
                relationDao.update(relationEntity,
                        new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                relationDao.insert(relationEntity);
            }
        }

    }

    /**
     * 根据分组id查找关联的所有属性(基本属性/规格参数)
     *
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getAttrRelation(Long attrgroupId) {

        List<AttrAttrgroupRelationEntity> relationList = relationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        List<Long> attrIds = relationList.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        if (attrIds == null || attrIds.size() == 0) {
            return null;
        }
        List<AttrEntity> attrEntityList = this.listByIds(attrIds);
        return attrEntityList;
    }

    /**
     * 删除对应分组和属性关联
     *
     * @param vos
     */
    @Override
    public void deleteRelation(AttrGroupRelationVO[] vos) {
        //发一次请求批量删除
        //DELETE FROM `pms_attr_attrgroup_relation`
        //WHERE (attr_id = ? and attr_group_id = ?) OR (attr_id = ? and attr_group_id = ?)
        List<AttrAttrgroupRelationEntity> relationList = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        System.out.println("------------------------" + relationList);
        relationDao.deleteBatchRelation(relationList);
    }

    /**
     * 获取当前分组还未关联的所有属性
     *
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoAttrRelation(Map<String, Object> params, Long attrgroupId) {
        //当前分组只能关联自己所属的分类里的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
/*        //查询自己未关联的属性集合
        List<AttrAttrgroupRelationEntity> relations = relationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIdList = relations.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());*/

        //当前分组只能关联别的分组还未引用的属性
        //1、当前分类下的其他分组
        List<AttrGroupEntity> groupList = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));
//                .ne("attr_group_id", attrgroupId));  //不能加这个条件, 否则查不出自己分组关联的属性
        List<Long> collectIds = groupList.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        //2、查询这些其他分组关联的属性
        List<AttrAttrgroupRelationEntity> relationList = relationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collectIds));
        List<Long> attrIds = relationList.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //3、从当前分类的所有属性中移除这些属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()); //只查基本属性,不查销售属性


        //判断非空
/*        //排除自己关联的属性
        boolean isBindSelf = attrIdList != null && attrIdList.size() > 0;  //判断本组是否有绑定属性
        boolean isBindOther = attrIds != null && attrIds.size() > 0;  //判断其他组是否有绑定属性
        if (isBindSelf || isBindOther){
            if (isBindSelf){
                attrIds.addAll(attrIdList);   //有关联的属性, 排除已关联过的属性
            }
            wrapper.notIn("attr_id", attrIds);
        }*/
        //排除别的组关联的属性
        if (attrIds != null && attrIds.size() > 0) {
            wrapper.notIn("attr_id", attrIds);
        }

        //是否有模糊查询
        String key = params.get("key").toString();
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> entityIPage = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        return new PageUtils(entityIPage);

    }

    @Override
    public Set<Long> selectSearchAttrIds(List<Long> attrIds) {

        List<AttrEntity> list = this.list(new LambdaQueryWrapper<AttrEntity>()
                .in(AttrEntity::getAttrId, attrIds)
                .and(w -> w.eq(AttrEntity::getSearchType, 1)));//1: 可检索
        if (CollectionUtil.isEmpty(list)){
            return new HashSet<>();
        }

        return list.stream().map(item -> item.getAttrId()).collect(Collectors.toSet());

    }


}
